package upload

import (
	"errors"
	"io"
	"mime/multipart"
	"os"
	"path"
	"strings"
	"time"
	"toy-car/pkg/util"
)

type Local struct{}

func (*Local) UploadFile(file *multipart.FileHeader) (string, string, error) {
	// 文件扩展名
	ext := path.Ext(file.Filename)

	name := strings.TrimSuffix(file.Filename, ext)
	name = util.MD5V([]byte(name))

	// 拼接新文件名
	filename := name + "_" + time.Now().Format("20060102250405") + ext

	mkdirErr := os.MkdirAll("./upload", os.ModePerm)

	if mkdirErr != nil {
		return "", "", errors.New("function os.MkdirAll() field, err :" + mkdirErr.Error())
	}

	p := "./upload/" + file.Filename
	f, openError := file.Open()
	if openError != nil {
		return "", "", errors.New("function file.Open() field, err :" + mkdirErr.Error())
	}

	defer f.Close()

	out, createErr := os.Create(p)
	if createErr != nil {
		return "", "", errors.New("function file.Create() field, err :" + mkdirErr.Error())
	}

	defer out.Close()

	_, copyErr := io.Copy(out, f)
	if copyErr != nil {
		return "", "", errors.New("function file.Copy() field, err :" + mkdirErr.Error())
	}
	return p, filename, nil
}

func (*Local) DeleteFile(key string) error {
	p := "./upload/" + key
	if strings.Contains(p, "./upload/") {
		if err := os.Remove(p); err != nil {
			return errors.New("删除本地文件失败, err:" + err.Error())
		}
	}
	return nil
}
